<?php

namespace App\Service\Collect;

use App\Service\Curl;
use App\Service\Xunsearch\Xunsearch;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use QL\QueryList;
use App\Models\Article;


class Base
{
    /**
     * 采集舆情文章
     *
     */

    protected $curl;  // 采集 实例化
    protected $error;
    protected $code;
    protected $ctime;  // 当前时间

    // 单独的
    protected $site_id;
    protected $site_name;
    // 开始日期 在之前的数据是不采集的 默认不设置
    protected $startTime;

    protected $keyword;
    protected $keywordId;

    // 初始化
    public function __construct()
    {
        $this->init();
    }

    // 初始化
    protected function init() { }

    // 获取错误信息
    public function getError()
    {
        return $this->error;
    }

    // 获取错误信息
    public function getCode()
    {
        return $this->code;
    }

    // 设置搜索的字段
    public function setKeyword($keyword)
    {
        $this->keyword = $keyword;
    }

    // 设置搜索的字段
    public function setKeywordId($keywordId)
    {
        $this->keywordId = $keywordId;
    }

    /**
     * 从网页中获取文章列表
     * @param $url  采集链接
     * @param $find 查询内容的位置：html元素
     * @param $range 将html分割成数组的规则
     * @param $rule 提取返回数据的规则
     * @return
     */
    protected function getQLList($url, $find, $range, $rule = [])
    {
        // 使用代理进行测试 测试结果：使用代理后，没有返回数据 只能使用curl
        //$proxy = ['http' => 'http://218.95.37.135:40465'];
        //$proxy = 'http://218.95.37.135:40465';
        //$proxy = '218.95.37.135:40465';

        //$proxy = ['http' => 'http://221.131.165.73:40294'];
        //$proxy = 'http://221.131.165.73:40294';
        //$proxy = 'http://221.131.165.73:40237';
        //$proxy = 'http://221.229.212.170:40026';
        //$proxy = 'http://221.229.212.170:40381';

        //$proxy = ['http' => 'http://221.229.212.170:40374'];
        //$proxy = 'http://221.229.212.170:40374';
        //$proxy = '221.229.212.170:40374';
        //$html = QueryList::get($url, [], ['proxy' => $proxy])->find($find)->html();


        // 执行采集
        //  如果采集的内容不是 utf-8 编码 则转换成utf-8
        //$html   = QueryList::get($url)->getHtml();
        $html   = QueryList::get($url)->find($find)->html();
        $encode = mb_detect_encoding($html, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"), true);
        if($encode != 'UTF-8'){
            $html = mb_convert_encoding($html, "UTF-8", $encode); //编码转换为utf-8
        }

        // 组合整理数据
        $ql   = QueryList::html($html);
        $list = $ql->range($range)->rules($rule)->queryData();

        return $list;
    }


    // 保存数据
    protected function saveArticle($data = [])
    {
        // || empty($data['author'])  || empty($data['title'])
        if(empty($data['link']) || empty($data['description']) || empty($data['from_site'])){
            return $this->return_false('保存数据库确实必须的字段！');
        }

        $time = $this->getCurrentTime();
        // 参数
        // 将全部参数放在开始的位置，方便以后查询查看，用于组合参数来调用该方法
        $title   = $data['title'];
        $_desc   = $data['description'];
        $_author = $data['author'] ?? '';
        $link    = $data['link'];
        $text    = $data['text'] ?? '';
        $ptime   = $data['time'] ?? $time;  // 发布时间
        // 各种数据
        $read_no    = $data['read_no'] ?? 0;
        $virtual_no = $data['virtual_no'] ?? 0;
        $collect_no = $data['collect_no'] ?? 0;
        $praise_no  = $data['praise_no'] ?? 0;
        $relay_no   = $data['relay_no'] ?? 0;
        $comment_no = $data['comment_no'] ?? 0;

        // 可能有的字段
        $_cover  = $data['cover'] ?? '';
        $_images = $data['images'] ?? '[]';
        // 这几个可以不用传递的数据
        $uid      = $data['uid'] ?? 0;
        $_channel = $data['from_channel'] ?? '';
        $_site    = $data['from_site'] ?? $this->site_name;
        $site_id  = $data['site_id'] ?? $this->site_id;

        ##########################################################
        // 实例化
        $userDb    = new \App\Models\User();
        $articleDb = new Article();
        // 描述
        $_desc  = mb_substr($_desc, 0, 900);
        $title  = mb_substr($title, 0, 200);
        $verify = 1; // 如果不展示为 -2
        if(is_array($_images)){
            $_images = json_encode($_images);
        }

        // 用户 来源 描述
        // 插入的操作
        $insert = [
            'author'       => $_author,
            'from_url'     => $link,
            'from_site'    => $_site,
            'from_channel' => $_channel,
            'title'        => $title,   // 标题
            'description'  => $_desc,
            'uid'          => $uid,
            'site_id'      => $site_id,
            'images'       => '[]',  //json_encode($images),  // 采集公众号的图片都为空
            'verify'       => $verify,
            'push_time'    => $ptime,
            'ctime'        => $time,
            'mtime'        => $time,

            // 各种数量
            'read_no'      => $read_no,
            'virtual_no'   => $virtual_no,
            'praise_no'    => $praise_no,
            'collect_no'   => $collect_no,
            'relay_no'     => $relay_no,
            'comment_no'   => $comment_no,

            // 可能有的字段
            'cover'        => $_cover,
            'images'       => $_images,

            // 没有使用的
            //'ip'          => 'ip地址',
            //'ip_address'  => '成都市',
            //'cate_id'     => '栏目id',
            //'keyword'     => '关键字',
            //'is_top'      => '是否置顶（1-是）',
        ];

        // 执行添加
        DB::beginTransaction();
        try{
            // 添加主表
            $news_id = $articleDb->insertGetId($insert);

            // 更新用户数据
            $numData = ['publish_no' => DB::raw("publish_no+1"), 'news_no' => DB::raw("news_no+1"),];
            $userDb->where('id', $uid)->update($numData);

            // 保存文章的股票信息
            /*foreach($stocks as $_id){
                $has[] = ['stock_id' => $_id, 'news_id' => $news_id, 'ctime' => $ctime];
            }
            if($has){
                $stockDb->insert($has);
            }*/

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->return_false($e->getMessage());
        }

        // TODO 添加到搜索引擎
        //$search = (new Xunsearch())->setDb('news');
        //$res    = $search->add($xun);

        // TODO 暂时测试采集，没有保存到财通社
        // 保存到财通社
        //$this->toCts($uid, $title, $item['digest'], $text);

        // 缓存操作
        $userDb->deleteCacheshow(['id' => $uid]);
        $articleDb->deleteCacheshow($insert);

        return true;
    }

    // 迅搜的组合
    protected function xunArray2String($array)
    {
        if(empty($array)){
            return '';
        }

        return '，'.implode('，', $array).'，';
    }


    // 删除 html 标签
    protected function removeHtml($_html, $allowed_tags = '<img><p>')
    {
        $encode = mb_detect_encoding($_html, array("ASCII", "UTF-8", "GB2312", "GBK", "BIG5"), true);
        if($encode != 'UTF-8'){
            $_html = mb_convert_encoding($_html, "UTF-8", $encode); //编码转换为utf-8
        }

        if(strpos($_html, '...') === 0){
            $_html = str_replace('...', '', $_html);
        }
        // 这里不直接用 $_item['text']  避免里面有图片
        // 先转换成实体符号，便于清理空格
        $_rangeHtml = htmlentities($_html);;
        $_rangeHtml = str_replace('&nbsp; ', '', $_rangeHtml);
        $_rangeHtml = str_replace('&nbsp;', '', $_rangeHtml);
        $_rangeHtml = str_replace('&#160;', '', $_rangeHtml);
        $_rangeHtml = str_replace('&#160; ', '', $_rangeHtml);
        //将实体符号转换成html标签，然后在删除html标签
        //$_rangeHtml = htmlspecialchars_decode($_rangeHtml);  // 只有部分实体符号转换
        $_rangeHtml = html_entity_decode($_rangeHtml);
        $_rangeHtml = strip_tags($_rangeHtml, $allowed_tags);
        $_rangeHtml = trim($_rangeHtml);

        //$_rangeHtml = htmlspecialchars($_rangeHtml);

        return $_rangeHtml;
    }

    // 判断是否已经采集
    protected function isGather($link)
    {
        // 查询链接是否存在
        // 如果已经采集 则不要在采集了
        $articleDb = new Article();
        $info      = $articleDb->where('from_url', $link)->first();

        return $info;
    }

    // 采集 针对于接口的采集使用
    protected function apiCurl()
    {
        if(empty($this->curl)){
            $this->curl = new Curl();
        }

        return $this->curl;
    }

    // 当前时间
    protected function getCurrentTime()
    {
        if(empty($this->ctime)){
            $this->ctime = time();
        }

        return $this->ctime;
    }

    // 微信群发
    public function toWechatGroup($title, $link, $weIds)
    {
        // 参数
        // $title = 'fffff总经理刚套现近700万，实控人、前董事长此前均被立案';
        // $link = 'https://www.baidu.com/';
        // $weIds = [61];

        // 组合
        $cookie = 'PHPSESSID=l64e9eetv265acqfoidv9krui2; aid=1; token=097eef40487211b5723e369d55bc2b48';
        $ctsUrl = 'https://plat.caitongnews.cn/API/Archive/sendWechat';
        $header = ['Cookie:'.$cookie, 'Content-Type:multipart/form-data'];
        $header = ['Cookie:'.$cookie, 'Content-Type:application/json'];
        $param  = ['subject' => $title, 'wechat_id' => $weIds, 'link' => $link];

        $curl = new Curl();
        $res  = $curl->url($ctsUrl)->header($header)->json($param)->request();
        $res  = json_decode($res, true);
        if($res){
            if($res['code'] = '0000'){
                return true;
            } else{
                $this->error = $res['msg'];

                return false;
            }
        }

        return true;
    }

    // 根据时间字符转换时间戳
    protected function toTimeStamp($string)
    {
        $dayPos = strpos($string, '天前');
        if($dayPos){
            $number = substr($string, 0, $dayPos);
            $stamp  = strtotime("-$number days");

            return $stamp;
        }

        return $this->getCurrentTime();
    }

    // 采集地址
    protected function realHref($_href, $domain = '')
    {
        // 如果不存在
        $pos = strpos($_href, 'http');
        if(($pos === false) || ($pos > 0)){
            if(strpos($_href, '//') === false){
                $_href = $domain.$_href;
            } else{
                $_href = 'https:'.$_href;
            }
        }

        return $_href;
    }

    ############################################################################################

    // 整理处理详情采集的内容
    protected function getShowContentCutQL($html)
    {
        return $html;
    }

    // 将图片都转换成整数（删除图片的时候可能是负数，比如删除最后一张是 -1）
    protected function numberToInteger($imgNumber, $count = 0)
    {
        $imgNumber = is_array($imgNumber) ? $imgNumber : [$imgNumber];
        if(empty($count)){
            return [];
        }
        $news = [];
        foreach($imgNumber as $_num){
            if($_num > 0){
                $news[] = $_num;
            } else{
                $news[] = $count + $_num + 1;
            }
        }

        return $news;
    }

    // 执行请求（发布到财通社：专栏）
    protected function toCts($uid, $author, $title, $desc, $content)
    {
        // 参数
        //$uid    = 564;
        //$author = '财通社';
        //$title  = '总经理刚套现近700万，实控人、前董事长此前均被立案';
        //$desc   = '<p>详情</p>';

        // 获取财通社的用户
        //$info   = $this->getCtsUser($uid);
        //$uid    = $info['id'] ?? 0;
        //$author = $info['name'] ?? '';
        $this->showMsg('       =====>转移到财通社用户id：'.$uid.' 用户：'.$author);

        // 采集的没有封面
        $cover = 'https://slh.caitongnews.com/images/2023/07/05/64a5575ce62d1.jpg';
        $cover = '';

        // 组合
        $cookie = 'PHPSESSID=l64e9eetv265acqfoidv9krui2; aid=1; token=097eef40487211b5723e369d55bc2b48';
        $ctsUrl = 'https://plat.caitongnews.cn/API/Archive/saveArchive';
        $header = ['Cookie:'.$cookie, 'Content-Type:multipart/form-data'];
        $header = ['Cookie:'.$cookie, 'Content-Type:application/json'];
        $param  = ['badge' => 'normal', 'category' => 'article', 'status' => 'enabled', 'author' => $author, 'original' => $author, 'cover' => $cover, 'desc' => $content, 'brief' => $desc, 'subject' => $title, 'tags' => $title, 'uid' => $uid];

        // 执行
        $api = $this->apiCurl();
        $rst = $api->url($ctsUrl)->header($header)->json($param)->request();
        $res = json_decode($rst, true);
        if($res['code'] = '0000'){
            return true;
        } else{
            return false;
        }
    }


    // TODO 财通社公众号的用户id
    protected function getCtsUser($uid)
    {
        if(empty($uid)){
            return [];
        }

        $ctsUsers = [

        ];
        $user     = $ctsUsers[$uid] ?? [];

        return $user;
    }

    ############################################################################################
    // 页面展示消息
    protected function showMsg($msg)
    {
        //$this->comment($msg);
        echo $msg.chr(10);
    }

    // 返回错误信息
    protected function return_false($msg = '操作失败！！', $code = 400)
    {
        $this->error = $msg;
        $this->code  = $code;

        return false;
    }

    // 返回错误，需要结束程序
    protected function return_die($msg = '操作失败！！')
    {
        $this->error = $msg;
        $this->code  = 500;

        return false;
    }

}
